class createTree {
  constructor(data, treeWrap, selectAll) {
    this.datas = data
    this.selectAll = selectAll
    this.treeWrap = treeWrap
    this.formatCompanyData = () => this
    this.formatCustomerData = () => this
    this.formatDepartmentData = () => this
    this.createHtml()
  }

  createHtml () {
    let html = ''

    html += '<div class="layui-container"><div style="float: left; border: 1px solid red;  height: 600px;min-width: 250px;margin-right: 10px;" id="tree1"></div><div style="float: left; border: 1px solid red;  height: 600px;min-width: 250px;margin-right: 10px;" id="tree2"></div><div style="float: left; border: 1px solid red;  height: 600px;min-width: 250px;margin-right: 10px;" id="tree3"></div></div>'

    $(this.treeWrap).html(html)
    this.createTypeTree()
  }

  createTypeTree () {
    const that = this
    const baseData = [
      {
        id: '1000000',
        title: '内部',
        arryName: 'innerList',
        nextArry: this.formatCompanyData(this.datas.innerList, 'innerList', '1000000')
      },
      {
        id: '1000001',
        title: '外部',
        arryName: 'outerList',
        children: [
          {
            id: '1000002',
            title: '好友公司',
            arryName: 'friendList',
            nextArry: this.formatCompanyData(this.datas.outerList.friendList, 'friendList', '1000002')
          },
          {
            id: '1000003',
            title: '客商',
            arryName: 'customerList',
            nextArry: this.formatCustomerData(this.datas.outerList.customerList, 'customerList', '1000002')
          },
          {
            id: '1000004',
            title: '供应商',
            arryName: '',
          }
        ]
      }
    ]
    layui.use(function () {
      var layer = layui.layer
        , form = layui.form
        , laypage = layui.laypage
        , element = layui.element
        , laydate = layui.laydate
        , tree = layui.tree
        , util = layui.util;
      tree.render({
        elem: '#tree1',  //绑定元素
        showCheckbox: true,
        onlyIconControl: true,
        data: baseData,
        id: 'demoId1',
        click: function (obj) {
          console.log(obj)
          // 二级树
          if (obj?.data?.nextArry) {
            Object.keys(obj.data.nextArry).forEach(item => {
              obj.data.nextArry[item].spread = true
              obj.data.nextArry[item].pid = obj.data.id // 子集赋予父id
            })
          }

          if (obj?.data?.children?.length) {
            // 检测子集是否全部选中
            let pNodeCheck = obj.data.children.every(item => { return item.checked })
            if (pNodeCheck) {
              that.renderTree2({ all: { id: obj.data.id, title: obj.data.title, checked: true } })
            } else {
              that.renderTree2(obj.data.nextArry)
            }
          } else {
            that.renderTree2(obj.data.nextArry)
          }

        },
        oncheck: function (obj) {
          console.log(obj)
          let nextArry = []
          obj.checked ? obj.data.checked = true : obj.data.checked = false
          // 当前树
          if (obj?.data?.children?.length) {
            obj.data.children.forEach(item => { // 给子集赋值方便后面使用
              obj.checked ? item.checked = true : item.checked = false
            })
          }

          // 下级树 （部分需要写成递归）
          if (obj?.data?.nextArry) {
            Object.keys(obj.data.nextArry).forEach(item => {
              // 有子项的不能直接设置checked !obj.data.nextArry[item].children.length
              if (obj.checked && !obj.data.nextArry[item]?.children?.length) {
                obj.data.nextArry[item].checked = true
              } else {
                obj.data.nextArry[item].checked = false
                // 如果有子集把所有子集设置选中  （只局限一组数据，根据需求变动下）
                if (obj.data.nextArry[item].children) {
                  obj.data.nextArry[item].children.forEach(item => {
                    obj.checked ? item.checked = true : item.checked = false
                    // obj.rootId = obj.data.id
                  })
                }
              }

              obj.data.nextArry[item].pid = obj.data.id // 子集赋予父id
              nextArry.push(obj.data.nextArry[item])
            })
          }

          // 对比当前选择和二级树是否为父子级关系 如果是刷新二级树数据
          let tree2Data = $('#tree2').find('input[type="checkbox"]').val()
          let isParent = nextArry.some(item => { return item.id === tree2Data })
          if (isParent) { // 如过是所属关系刷新数据
            that.renderTree2(obj.data.nextArry)
          }
        }
      })
    })
  }

  renderTree2 (itemData) {
    let data = []
    if (!itemData) {
      itemData = []
    }
    Object.keys(itemData).forEach(item => {
      data.push(itemData[item])
    })
    layui.use(function () {
      var layer = layui.layer
        , form = layui.form
        , laypage = layui.laypage
        , element = layui.element
        , laydate = layui.laydate
        , tree = layui.tree
        , util = layui.util;
      tree.render({
        elem: '#tree2',  //绑定元素
        showCheckbox: true,
        onlyIconControl: true,
        data: data,
        id: 'demoId2',
        click: function (obj) {
          // 三级树
          if (obj?.data?.childrens?.length) {
            obj.data.childrens.forEach(item => {
              item.spread = true
              item.pid = obj.data.id // 子集赋予父id
            })
          }
          renderTree3(obj.data.childrens)
        },
        oncheck: function (obj) {
          obj.checked ? obj.data.checked = true : obj.data.checked = false

          let tree2CheckArry = []
          let tree2CheckN = $('#tree2').find('input[type="checkbox"]')
          for (let i = 0; i < tree2CheckN.length; i++) {
            tree2CheckArry.push($(tree2CheckN[i]).prop('checked'))
          }

          // 检测是否全部取消选中 去取消一级树选中
          let noParentCheck = tree2CheckArry.every(item => { return !item })
          let isParentCheck = tree2CheckArry.every(item => { return item })

          // 父节点操作
          let nodeId = obj.data.rootId ? obj.data.rootId : obj.data.pid
          let setNode = $('#tree1 .layui-tree-set').find('input[value="' + nodeId + '"]')

          if (noParentCheck) { // 全部取消
            if (setNode.prop('checked')) {
              setNode.next().click()
            }
          }

          if (isParentCheck) { // 全部选中
            if (!setNode.prop('checked')) {
              setNode.next().click()
            }
          }


          // 操作3级
          let nextArry = []
          if (obj?.data?.childrens) {
            obj.data.childrens.forEach(item => {
              obj.checked ? item.checked = true : item.checked = false
              item.spread = true
            })
          }



          // 下级树 （部分需要写成递归）
          if (obj?.data?.childrens) {
            Object.keys(obj.data.childrens).forEach(item => {
              // 有子项的不能直接设置checked !obj.data.nextArry[item].children.length
              if (obj.checked && !obj.data.childrens[item]?.children?.length) {
                obj.data.childrens[item].checked = true
              } else {
                obj.data.childrens[item].checked = false
                // 如果有子集把所有子集设置选中  （只局限一组数据，根据需求变动下）
                if (obj.data.childrens[item].children) {
                  obj.data.childrens[item].childrens.forEach(item => {
                    obj.checked ? item.checked = true : item.checked = false
                    // obj.rootId = obj.data.id
                  })
                }
              }

              obj.data.childrens[item].pid = obj.data.id // 子集赋予父id
              nextArry.push(obj.data.childrens[item])
            })
          }

          // 对比当前选择和三级级树是否为父子级关系 如果是刷新三级树数据
          let tree3Data = $('#tree3').find('input[type="checkbox"]').val()
          let isParent = nextArry.some(item => { return item.id === tree3Data })
          if (isParent) { // 如过是所属关系刷新数据
            renderTree3(obj.data.childrens)
          }
        }
      })
    })

  }

  formatCompanyData (data, t, id = 0) {
    Object.keys(data).map(k => {
      data[k].ftype = t
      data[k].name ? data[k].title = data[k].name : ''
      data[k].pid = id
      if (data[k].hasOwnProperty('children') && Object.keys(data[k].children).length > 0) {
        formatCompanyData(data[k].children, t, data[k].id)

        data[k].childrens = Object.values(data[k].children)
        if (data[k].type === 'company' || data[k].type === 'customer') {
          let arr = []
          Object.values(data[k].children).map(obj => {
            if (obj.type === 'company' || obj.type === 'customer') {
              arr.push(obj)
            }
          })
          data[k].children = arr
        }
      }
    })
    return Object.values(data)
  }

  formatDepartmentData (data, isChecked) {
    let arr = []
    data.map(obj => {
      if (obj.type !== 'company') {
        obj.checked = isChecked
        if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
          obj.children = obj.childrens
          formatDepartmentData(obj.childrens, isChecked)
        }
        arr.push(obj)
      }
    })
    return arr
  }
  
  formatCustomerData (data, t, id) {
    let arr = []
    Object.values(data).map(obj => {
      obj.ftype = t
      obj.pid = id
      obj.title = obj.name
      arr.push(obj)
    })
    return arr
  }

}